﻿using Microsoft.Extensions.ObjectPool;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace zijian666.Data
{
    internal static class ObjectPoolHelper
    {
        public readonly struct Retrunable<T> : IDisposable
            where T : class
        {
            readonly ObjectPool<T> _pool;
            readonly T _value;

            public Retrunable(ObjectPool<T> pool, T value)
            {
                _pool = pool ?? throw new ArgumentNullException(nameof(pool));
                _value = value;
            }

            public void Dispose() => _pool.Return(_value);
        }


        private static ObjectPool<StringBuilder> _stringBuilderPool = ObjectPool.Create(new StringBuilderPooledObjectPolicy());

        public static Retrunable<StringBuilder> GetStringBuilder(out StringBuilder stringBuilder)
        {
            stringBuilder = _stringBuilderPool.Get();
            return new Retrunable<StringBuilder>(_stringBuilderPool, stringBuilder);
        }

        private static ObjectPool<DbParameterFormatProvider> _pfpPool = ObjectPool.Create(new PooledObjectPolicy<DbParameterFormatProvider>());

        public static Retrunable<DbParameterFormatProvider> GetDbParameterFormatProvider(out DbParameterFormatProvider provider)
        {
            provider = _pfpPool.Get();
            return new Retrunable<DbParameterFormatProvider>(_pfpPool, provider);
        }

        private static ObjectPool<Stopwatch> _stopwatchPool = ObjectPool.Create(new PooledObjectPolicy<Stopwatch>(x => x.Reset()));

        public static Retrunable<Stopwatch> GetStopwatch(out Stopwatch stopwatch)
        {
            stopwatch = _stopwatchPool.Get();
            return new Retrunable<Stopwatch>(_stopwatchPool, stopwatch);
        }
    }
}
